package w83b.ejie.general.filters;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class W83bFilteredRequest extends HttpServletRequestWrapper {

        public W83bFilteredRequest(ServletRequest request) {
                super((HttpServletRequest)request);
        }

        public String sanitize(String input) {
                String result = "";
                
                try {
					result = URLDecoder.decode(URLEncoder.encode((String)input, "ISO-8859-1"), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
                return result;
        }

        public String getParameter(String paramName) {
                String value = super.getParameter(paramName);
                	if(null!=value 
                			&& null!=paramName
                			&& !encontrarTildesEnyes(value)                			
                			){
                        value = sanitize(value);//NOPMD
                	}

                return value;
        }
        
        public boolean encontrarTildesEnyes(String palabra){
        	
        	if(null!=palabra
        			&&(-1!=palabra.toUpperCase().indexOf("Ñ")
        			||-1!=palabra.toUpperCase().indexOf("Á")
        			||-1!=palabra.toUpperCase().indexOf("É")
        			||-1!=palabra.toUpperCase().indexOf("Í")
        			||-1!=palabra.toUpperCase().indexOf("Ó")
        			||-1!=palabra.toUpperCase().indexOf("Ú")
        			||-1!=palabra.toUpperCase().indexOf("º")
        			||-1!=palabra.toUpperCase().indexOf("ª")
        			||-1!=palabra.toUpperCase().indexOf("Ä")
        			||-1!=palabra.toUpperCase().indexOf("Ë")
        			||-1!=palabra.toUpperCase().indexOf("Ï")
        			||-1!=palabra.toUpperCase().indexOf("Ö")
        			||-1!=palabra.toUpperCase().indexOf("Ü")
        			)){
        		return true;
        	}
        	return false;
        }

        public String[] getParameterValues(String paramName) {
                String values[] = super.getParameterValues(paramName);
                if(null!=values){
	                for (int index = 0; index < values.length; index++) {
	                        	if(null!=values[index] 
	                        	                && null!=paramName
	                                			
	                        	                && !encontrarTildesEnyes(values[index]) 
	                                			){
	                                values[index] = sanitize(values[index]);//NOPMD
	                        }
	                }
                }
                return values;
        }
    }
